#!/usr/bin/env python3
import json
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed

sys.path.insert(0, '.')
from server_stress_advanced import ChaosBladeManager

def detect_blade_path(manager, server):
    cmd = "which blade 2>/dev/null || find /root /usr/local /opt /home -name blade -type f 2>/dev/null | grep chaosblade | head -1"

    result = manager.execute_ssh_command(
        server['host'],
        server['username'],
        server['password'],
        cmd,
        server.get('port', 22),
        timeout=60
    )

    blade_path = result['output'].strip()

    return {
        'host': server['host'],
        'blade_path': blade_path if blade_path else 'NOT_FOUND',
        'success': result['success'] and bool(blade_path)
    }

def main():
    with open('servers.json', 'r', encoding='utf-8') as f:
        config = json.load(f)

    manager = ChaosBladeManager('servers.json')
    servers = config['servers']

    print(f"开始检测 {len(servers)} 台服务器的ChaosBlade路径...\n")

    results = []
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = {executor.submit(detect_blade_path, manager, server): server for server in servers}

        for future in as_completed(futures):
            result = future.result()
            results.append(result)

            if result['success']:
                print(f"✓ {result['host']:<18} → {result['blade_path']}")
            else:
                print(f"✗ {result['host']:<18} → {result['blade_path']}")

    print("\n" + "="*80)
    print("路径统计：")
    print("="*80)

    path_groups = {}
    for result in results:
        path = result['blade_path']
        if path not in path_groups:
            path_groups[path] = []
        path_groups[path].append(result['host'])

    for path, hosts in sorted(path_groups.items()):
        print(f"\n路径: {path}")
        print(f"服务器数量: {len(hosts)}")
        print(f"服务器列表: {', '.join(hosts[:5])}" + (f" ... (+{len(hosts)-5}台)" if len(hosts) > 5 else ""))

    print("\n" + "="*80)
    print("生成配置建议：")
    print("="*80)

    if len(path_groups) == 1:
        common_path = list(path_groups.keys())[0]
        if common_path != 'NOT_FOUND':
            print(f"\n所有服务器使用相同路径，可以统一配置：")
            print(f"sed -i 's|\"chaosblade_path\":.*|\"chaosblade_path\": \"{common_path}\",|g' servers.json")
        else:
            print("\n⚠ 所有服务器都未找到ChaosBlade，请先安装ChaosBlade")
    else:
        print("\n服务器使用不同的ChaosBlade路径，需要分组配置。")
        print("建议方案：为不同路径的服务器创建不同的配置文件\n")

        for idx, (path, hosts) in enumerate(sorted(path_groups.items()), 1):
            if path != 'NOT_FOUND':
                print(f"# 配置文件 {idx}: servers_group{idx}.json")
                print(f"# 路径: {path}")
                print(f"# 服务器: {len(hosts)}台")
                print(f"# 使用: python3 server_stress_advanced.py cpu --cpu-percent 30 --config servers_group{idx}.json\n")

    with open('blade_path_detection.json', 'w', encoding='utf-8') as f:
        json.dump(results, f, ensure_ascii=False, indent=2)

    print("\n检测结果已保存到: blade_path_detection.json")

if __name__ == '__main__':
    main()
